// 初始化游戏
const gridSize = {rows: 8, cols: 10};
let grid = [];
let targetColor = '';
let stepsLeft = 15;

// 颜色选项
const colors = ['red', 'blue', 'green', 'yellow'];

// 初始化网格
function initGrid() {
  grid = new Array(gridSize.rows).fill().map(() => 
    new Array(gridSize.cols).fill().map(() => 
      colors[Math.floor(Math.random() * colors.length)]
    )
  );
  renderGrid();
}

// 渲染网格
function renderGrid() {
  const gridElement = document.getElementById('grid');
  gridElement.innerHTML = '';

  grid.forEach((row, i) => {
    row.forEach((color, j) => {
      const cell = document.createElement('div');
      cell.className = 'cell';
      cell.setAttribute('data-row', i);
      cell.setAttribute('data-col', j);
      cell.style.backgroundColor = color;
      cell.addEventListener('click', () => handleCellClick(i, j));
      gridElement.appendChild(cell);
    });
  });
}

// 处理格子点击
async function handleCellClick(row, col) {
  if (stepsLeft <= 0) return;

  const selectedColor = document.querySelector('.color-btn.selected')?.dataset.color;
  if (!selectedColor) return;

  const originalColor = grid[row][col];
  if (selectedColor === originalColor) return;

  await floodFill(row, col, originalColor, selectedColor);
  stepsLeft--;
  updateStatus();
  renderGrid();
  checkWinCondition();
}

// 洪水填充算法
async function floodFill(row, col, originalColor, newColor) {
  if (row < 0 || row >= gridSize.rows || col < 0 || col >= gridSize.cols) return;
  if (grid[row][col] !== originalColor) return;

  const cell = document.querySelector(`[data-row='${row}'][data-col='${col}']`);
  cell.style.setProperty('--from-color', originalColor);
  cell.style.setProperty('--to-color', newColor);
  cell.style.animation = 'colorChange 1s ease';
  cell.style.animationPlayState = 'running';
  cell.style.backgroundColor = newColor;
  grid[row][col] = newColor;

  await new Promise(resolve => setTimeout(resolve, 200));

  // 四向扩散
  await floodFill(row + 1, col, originalColor, newColor);
  await floodFill(row - 1, col, originalColor, newColor);
  await floodFill(row, col + 1, originalColor, newColor);
  await floodFill(row, col - 1, originalColor, newColor);
}

// 更新状态
function updateStatus() {
  document.getElementById('status').textContent = `剩余步数：${stepsLeft}`;
}

// 检查胜利条件
function checkWinCondition() {
  const allMatchTarget = grid.flat().every(color => color === targetColor);
  if (allMatchTarget) {
    alert('恭喜你赢了！');
    resetGame();
  } else if (stepsLeft <= 0) {
    alert('游戏结束，步数用尽！');
    resetGame();
  }
}

// 重置游戏
function resetGame() {
  initGrid();
  targetColor = colors[Math.floor(Math.random() * colors.length)];
  stepsLeft = 15;
  updateStatus();
  document.getElementById('target-color').querySelector('.color-btn').style.backgroundColor = targetColor;
    document.getElementById('target-color').querySelector('.color-btn').style.transition = 'background-color 0.3s ease';
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
  // 设置颜色按钮点击事件
  document.querySelectorAll('.color-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.color-btn').forEach(b => b.classList.remove('selected'));
      btn.classList.add('selected');
    });
  });

  // 设置开始按钮点击事件
  document.getElementById('start-btn').addEventListener('click', resetGame);

  // 初始化游戏
  resetGame();
});